package com.tao.com.xiaowen.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tao.com.xiaowen.R;
import com.tao.com.xiaowen.config.sqlite.DatabaseUtils;
import com.tao.com.xiaowen.config.tecent.GetUserAuth;
import com.tao.com.xiaowen.model.Favorite;
import com.tao.com.xiaowen.model.JokeData;
import com.tao.com.xiaowen.model.Model;
import com.tao.com.xiaowen.module.me.LoginActivity;
import com.tencent.tauth.Tencent;

import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by Administrator on 2016/8/4.
 */
public class PicJokeAdapter extends RecyclerView.Adapter<PicJokeAdapter.TextJokeViewHolder> {
    private Context context;
    private List<JokeData> jokeList;
    private LayoutInflater inflater;
    private OnItemClickListener onItemClickListener;

    private boolean isClick = false;
    private boolean isFavorite = false;
    private int p = -1;
    private int q = -1;

    private Tencent tencent;
    private long time = 0;
    private BmobUser bmobUser;
    private JokeData jd;
    private BmobRelation relation;
    private String expires_in = null;

    public PicJokeAdapter(Context context, List<JokeData> jokeList) {
        this.context = context;
        this.jokeList = jokeList;
        inflater = LayoutInflater.from(context);
    }

    public void OnItemClick(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @Override
    public TextJokeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.fragment_joke_item, null);
        TextJokeViewHolder holder = new TextJokeViewHolder(view);
        Bmob.initialize(context, Model.APP_ID_BMOB);
        tencent = Tencent.createInstance(Model.APP_ID_QQ, context);

        return holder;
    }

    @Override
    public void onBindViewHolder(final TextJokeViewHolder holder, final int position) {
        final JokeData joke = jokeList.get(position);
        holder.content.setText(joke.getContent());
        holder.picUrl.setVisibility(View.VISIBLE);

        Glide.with(context).load(joke.getUrl())
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .placeholder(R.drawable.default_content_pic)
                .error(R.drawable.default_content_pic)
                .crossFade()
                .into(holder.picUrl);

        initNum(holder, position);

        holder.supportTbas.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.support:
                        if (p != position) {
                            isClick = false;
                        }
                        if (isClick) {
                            joke.setSupportNum(Integer.valueOf((String) holder.happyNum.getText()) + 2);
                        } else {
                            joke.setSupportNum(Integer.valueOf((String) holder.happyNum.getText()) + 1);
                        }
                        p = position;

                        jd = new JokeData();
                        bmobUser = BmobUser.getCurrentUser();
                        relation = new BmobRelation();
                        relation.add(bmobUser);
                        jd.setLikes(relation);
                        jd.setSupportNum(joke.getSupportNum());
                        jd.setClick(isClick);
                        jd.update(joke.getObjectId(), new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                initNum(holder, position);
                            }
                        });
                        break;
                    case R.id.unsupport:
                        if (p != position) {
                            isClick = false;
                        } else {
                            isClick = true;
                        }

                        if (isClick) {
                            joke.setSupportNum(Integer.valueOf((String) holder.happyNum.getText()) - 2);
                        } else {
                            joke.setSupportNum(Integer.valueOf((String) holder.happyNum.getText()) - 1);
                        }
                        p = position;

                        jd = new JokeData();
                        bmobUser = BmobUser.getCurrentUser();
                        relation = new BmobRelation();
                        relation.add(bmobUser);
                        jd.setLikes(relation);
                        jd.setSupportNum(joke.getSupportNum());
                        jd.setClick(isClick);
                        jd.update(joke.getObjectId(), new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                initNum(holder, position);
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        });

        bmobUser = BmobUser.getCurrentUser();
        expires_in = GetUserAuth.getUserAyth(tencent, context);
        if (expires_in != null) {
            time = System.currentTimeMillis() + Long.parseLong(expires_in) * 1000;
        } else {
            time = 0;
        }

        if (onItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onItemClickListener.OnItemClick(view, position);
                }
            });
        }


        holder.myfavoriteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (time > 0 || bmobUser != null) {
                    if (q != position) {
                        isFavorite = false;
                    }
                    if (!isFavorite) {
                        holder.myfavoriteBtn.setImageResource(R.drawable.joke_favorite_pressed);
                        DatabaseUtils.initHelper(context, "favorite.db");
                        Favorite favorite = new Favorite();
                        favorite.setContent(joke.getContent());
                        favorite.setPicture(joke.getPicture());
                        favorite.set_id(position);
                        DatabaseUtils.getHelper().save(favorite);
                        isFavorite = true;
                        q = position;
                        Toast.makeText(context, "收藏成功!", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, "已经收藏了！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Intent intent = new Intent(context, LoginActivity.class);
                    context.startActivity(intent);
                }
            }
        });
    }

    public void initNum(final TextJokeViewHolder holder, int position) {
        final JokeData joke = jokeList.get(position);
        BmobQuery<JokeData> query = new BmobQuery<JokeData>();
        query.order("created");
        query.findObjects(new FindListener<JokeData>() {
            @Override
            public void done(List<JokeData> list, BmobException e) {
                if (list != null) {
                    for (JokeData jp : list) {
                        if (joke.getHashId().equals(jp.getHashId())) {
                            holder.happyNum.setText(String.valueOf(jp.getSupportNum()));
                        }
                    }
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return jokeList.size();
    }

    class TextJokeViewHolder extends RecyclerView.ViewHolder {
        private TextView content;
        private ImageView picUrl;
        private TextView happyNum;
        private RadioButton supportBtn;
        private RadioButton unsupportBtn;
        private RadioGroup supportTbas;
        private ImageButton myfavoriteBtn;

        public TextJokeViewHolder(View itemView) {
            super(itemView);
            content = (TextView) itemView.findViewById(R.id.content);
            picUrl = (ImageView) itemView.findViewById(R.id.picUrl);
            happyNum = (TextView) itemView.findViewById(R.id.happy_num);
            supportBtn = (RadioButton) itemView.findViewById(R.id.support);
            unsupportBtn = (RadioButton) itemView.findViewById(R.id.unsupport);
            supportTbas = (RadioGroup) itemView.findViewById(R.id.tabs);
            myfavoriteBtn = (ImageButton) itemView.findViewById(R.id.my_favorite);
        }
    }

    public interface OnItemClickListener {
        void OnItemClick(View view, int position);
    }
}
